<?php
/**
 * 修复建行回调502错误
 * cront定时每分钟运行一次
 */
$fixlogFile = 'fix.log';
$accesslogFile = 'proxy-access.log';

$fixlogFile = '/root/script/fix.log';
$accesslogFile = '/var/log/nginx/proxy-access.log';

$fixlog = @file_get_contents($fixlogFile);
$fixlog = explode("\n", $fixlog);

$accesslog = file_get_contents($accesslogFile);
$accesslog = explode("\n", $accesslog);
$log = '';
foreach ($accesslog as $item) {
    $itemArr = explode(' ', $item);
    if (isset($itemArr[8]) && '502' == $itemArr[8] && false !== strpos($itemArr['6'], '/notify/JianHangpay')) {
        if (!in_array($itemArr[6], $fixlog)) {
            $url = 'http://juyouzhifu.com'.$itemArr[6];
            $result = request($url);
            $log .= date('Y-m-d H:i:s')."\nRequest: {$url}\nResult: {$result}\n";
            if ('0000' === $result) {
                $fixlog[] = $itemArr[6];
                file_put_contents($fixlogFile, $itemArr[6]."\n", FILE_APPEND);
            }
        }
    }
}
if (strlen($log) > 0) {
    $sms = [
        'msgtype' => 'text',
        'text' => [
            'content' => "补单Result: {$log}",
        ],
    ];

    $res = request('https://oapi.dingtalk.com/robot/send?access_token=89dfc1db08182057116660c3526b5027056642c41da8a2f6fc394fdddc63edda', true, json_encode($sms), ['Content-Type: application/json;charset=utf-8']);
}

function request($url, $isPost = false, $postData = [], $head = '')
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
    // 告诉curl禁用ssl当中的公用名,公用名只有两种值0表没有，1表示拥有，默认为1
    // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    // curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    //执行命令
    if (count($head) > 0) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $head);
    }
    if ($isPost) {
        var_dump($postData);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
    }

    $str = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);
    //把请求的数据进行返回
    return $str;
}
